const fs = require('fs');
const path = require('path');
const inquirer = require('inquirer');
const chalk = require('chalk');
const ora = require('ora');

class DemoGenerator {
  constructor() {
    this.demosDir = path.join(__dirname, '..', 'src', 'demos');
    this.templatesDir = path.join(__dirname, 'templates');
    this.ensureTemplatesExist();
  }

  ensureTemplatesExist() {
    if (!fs.existsSync(this.templatesDir)) {
      fs.mkdirSync(this.templatesDir, { recursive: true });
      this.createDefaultTemplates();
    }
  }

  createDefaultTemplates() {
    // HTML模板
    const htmlTemplate = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <div class="demo-container">
        <h1>{{title}}</h1>
        <!-- 在这里添加您的HTML内容 -->
        <div class="demo-content">
            <p>这是一个示例内容，请替换为您自己的内容。</p>
        </div>
    </div>
    <script src="index.js"></script>
</body>
</html>`;

    // CSS模板
    const cssTemplate = `/* {{title}} 样式 */
.demo-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    font-family: 'Arial', sans-serif;
    color: white;
}

.demo-content {
    background: rgba(255, 255, 255, 0.1);
    padding: 2rem;
    border-radius: 10px;
    backdrop-filter: blur(10px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

h1 {
    font-size: 2.5rem;
    margin-bottom: 2rem;
    text-align: center;
}

/* 在这里添加您的自定义样式 */`;

    // JavaScript模板
    const jsTemplate = `// {{title}} 交互逻辑
document.addEventListener('DOMContentLoaded', function() {
    console.log('{{title}} 已加载');
    
    // 在这里添加您的JavaScript代码
    const container = document.querySelector('.demo-container');
    
    // 示例：添加点击事件
    container.addEventListener('click', function() {
        console.log('容器被点击了！');
    });
});`;

    fs.writeFileSync(path.join(this.templatesDir, 'index.html'), htmlTemplate);
    fs.writeFileSync(path.join(this.templatesDir, 'index.css'), cssTemplate);
    fs.writeFileSync(path.join(this.templatesDir, 'index.js'), jsTemplate);
  }

  async generate() {
    console.log(chalk.blue.bold('🎨 前端案例生成器'));
    console.log(chalk.gray('快速创建新的前端样式案例\n'));

    try {
      const answers = await this.promptForDemoInfo();
      await this.createDemo(answers);
    } catch (error) {
      console.error(chalk.red('生成失败:'), error.message);
      process.exit(1);
    }
  }

  async promptForDemoInfo() {
    const questions = [
      {
        type: 'input',
        name: 'name',
        message: '请输入案例名称:',
        validate: (input) => {
          if (!input.trim()) {
            return '案例名称不能为空';
          }
          // 检查案例名称是否已存在
          if (this.isDemoNameExists(input.trim())) {
            return '案例名称已存在，请使用其他名称';
          }
          return true;
        }
      },
      {
        type: 'list',
        name: 'category',
        message: '请选择案例分类:',
        choices: [
          { name: '按钮 (buttons)', value: 'buttons' },
          { name: '图标 (icons)', value: 'icons' },
          { name: '加载 (loadings)', value: 'loadings' },
          { name: '导航栏 (navigations)', value: 'navigations' },
          { name: '卡片 (cards)', value: 'cards' },
          { name: '表单 (forms)', value: 'forms' },
          { name: '动画 (animations)', value: 'animations' },
          { name: '布局 (layouts)', value: 'layouts' }
        ]
      },
      {
        type: 'input',
        name: 'folderName',
        message: '请输入文件夹名称 (留空自动生成):',
        validate: (input) => {
          if (!input.trim()) {
            return true; // 允许为空，将使用自动生成的名称
          }
          // 检查文件夹名称是否已存在
          const demosDir = path.join(__dirname, '..', 'src', 'demos');
          const folderPath = path.join(demosDir, input.trim());
          if (fs.existsSync(folderPath)) {
            return '文件夹名称已存在，请使用其他名称';
          }
          return true;
        },
        default: function(answers) {
          // 生成下一个可用的数字文件夹名
          const demosDir = path.join(__dirname, '..', 'src', 'demos');
          let existingFolders = [];
          
          try {
            if (fs.existsSync(demosDir)) {
              existingFolders = fs.readdirSync(demosDir, { withFileTypes: true })
                .filter(dirent => dirent.isDirectory())
                .map(dirent => dirent.name)
                .filter(name => /^\d+$/.test(name))
                .map(name => parseInt(name))
                .sort((a, b) => a - b);
            }
          } catch (error) {
            // 如果读取目录失败，使用默认值
            existingFolders = [];
          }

          const nextNumber = existingFolders.length > 0 ? Math.max(...existingFolders) + 1 : 1;
          return nextNumber.toString().padStart(3, '0');
        }
      },
      {
        type: 'confirm',
        name: 'includeJS',
        message: '是否包含JavaScript文件?',
        default: true
      },
      {
        type: 'confirm',
        name: 'openInEditor',
        message: '生成后是否在编辑器中打开?',
        default: true
      }
    ];

    return await inquirer.prompt(questions);
  }

  generateFolderName(name) {
    // 生成下一个可用的数字文件夹名
    const existingFolders = fs.readdirSync(this.demosDir, { withFileTypes: true })
      .filter(dirent => dirent.isDirectory())
      .map(dirent => dirent.name)
      .filter(name => /^\d+$/.test(name))
      .map(name => parseInt(name))
      .sort((a, b) => a - b);

    const nextNumber = existingFolders.length > 0 ? Math.max(...existingFolders) + 1 : 1;
    return nextNumber.toString().padStart(3, '0');
  }

  isDemoNameExists(name) {
    try {
      const demoJSPath = path.join(__dirname, '..', 'src', 'scripts', 'demo.js');
      if (!fs.existsSync(demoJSPath)) {
        return false;
      }
      
      const content = fs.readFileSync(demoJSPath, 'utf8');
      // 检查案例名称是否已存在于demo.js中
      return content.includes(`name: "${name}"`);
    } catch (error) {
      return false;
    }
  }

  isFolderNameExists(folderName) {
    try {
      const folderPath = path.join(this.demosDir, folderName);
      return fs.existsSync(folderPath);
    } catch (error) {
      return false;
    }
  }

  async createDemo(answers) {
    const spinner = ora('正在生成案例...').start();
    
    try {
      const folderName = answers.folderName || this.generateFolderName(answers.name);
      const demoPath = path.join(this.demosDir, folderName);
      
      // 确保demos目录存在
      if (!fs.existsSync(this.demosDir)) {
        fs.mkdirSync(this.demosDir, { recursive: true });
      }
      
      // 检查文件夹是否已存在
      if (fs.existsSync(demoPath)) {
        throw new Error(`文件夹 ${folderName} 已存在`);
      }

      // 创建文件夹
      fs.mkdirSync(demoPath, { recursive: true });

      // 生成文件
      await this.generateFiles(demoPath, answers);

      // 更新demo.js文件
      await this.updateDemoJS(answers.name, folderName, answers.category);

      spinner.succeed(`案例 "${answers.name}" 生成成功！`);
      
      console.log(chalk.green(`\n✅ 案例已创建:`));
      console.log(chalk.cyan(`   文件夹: src/demos/${folderName}`));
      console.log(chalk.cyan(`   分类: ${answers.category}`));
      console.log(chalk.cyan(`   文件: index.html, index.css${answers.includeJS ? ', index.js' : ''}`));
      console.log(chalk.cyan(`   已更新: demo.js 文件`));
      console.log(chalk.yellow(`   注意: 请手动添加预览图到 images/previews/${folderName}.webp`));

      // 在编辑器中打开
      if (answers.openInEditor) {
        await this.openInEditor(demoPath);
      }

      console.log(chalk.yellow(`\n💡 提示:`));
      console.log(chalk.gray(`   - 编辑 src/demos/${folderName}/index.html 添加您的HTML内容`));
      console.log(chalk.gray(`   - 编辑 src/demos/${folderName}/index.css 添加您的样式`));
      if (answers.includeJS) {
        console.log(chalk.gray(`   - 编辑 src/demos/${folderName}/index.js 添加您的交互逻辑`));
      }
      console.log(chalk.gray(`   - 运行 npm run build 重新构建项目`));

    } catch (error) {
      spinner.fail('生成失败');
      throw error;
    }
  }

  async generateFiles(demoPath, answers) {
    const templates = {
      html: fs.readFileSync(path.join(this.templatesDir, 'index.html'), 'utf8'),
      css: fs.readFileSync(path.join(this.templatesDir, 'index.css'), 'utf8'),
      js: fs.readFileSync(path.join(this.templatesDir, 'index.js'), 'utf8')
    };

    // 替换模板变量
    const replacements = {
      title: answers.name,
      category: answers.category
    };

    // 生成HTML文件
    let htmlContent = templates.html;
    Object.entries(replacements).forEach(([key, value]) => {
      htmlContent = htmlContent.replace(new RegExp(`{{${key}}}`, 'g'), value);
    });
    fs.writeFileSync(path.join(demoPath, 'index.html'), htmlContent);

    // 生成CSS文件
    let cssContent = templates.css;
    Object.entries(replacements).forEach(([key, value]) => {
      cssContent = cssContent.replace(new RegExp(`{{${key}}}`, 'g'), value);
    });
    fs.writeFileSync(path.join(demoPath, 'index.css'), cssContent);

    // 生成JavaScript文件（如果需要）
    if (answers.includeJS) {
      let jsContent = templates.js;
      Object.entries(replacements).forEach(([key, value]) => {
        jsContent = jsContent.replace(new RegExp(`{{${key}}}`, 'g'), value);
      });
      fs.writeFileSync(path.join(demoPath, 'index.js'), jsContent);
    }
  }


  async openInEditor(demoPath) {
    try {
      // 尝试使用系统默认编辑器打开
      const { exec } = require('child_process');
      const platform = process.platform;
      
      let command;
      if (platform === 'darwin') {
        command = `open "${demoPath}"`;
      } else if (platform === 'win32') {
        command = `start "" "${demoPath}"`;
      } else {
        command = `xdg-open "${demoPath}"`;
      }
      
      exec(command, (error) => {
        if (error) {
          console.log(chalk.yellow('无法自动打开编辑器，请手动打开文件夹'));
        }
      });
    } catch (error) {
      console.log(chalk.yellow('无法自动打开编辑器，请手动打开文件夹'));
    }
  }

  // 批量生成工具
  async generateBatch() {
    console.log(chalk.blue.bold('📦 批量生成工具'));
    
    const questions = [
      {
        type: 'input',
        name: 'count',
        message: '请输入要生成的数量:',
        validate: (input) => {
          const num = parseInt(input);
          if (isNaN(num) || num <= 0) {
            return '请输入有效的数字';
          }
          return true;
        }
      },
      {
        type: 'input',
        name: 'prefix',
        message: '请输入名称前缀:',
        default: '示例案例'
      },
      {
        type: 'list',
        name: 'category',
        message: '请选择分类:',
        choices: [
          { name: '按钮 (buttons)', value: 'buttons' },
          { name: '动画 (animations)', value: 'animations' },
          { name: '加载 (loadings)', value: 'loadings' }
        ]
      }
    ];

    const answers = await inquirer.prompt(questions);
    const count = parseInt(answers.count);
    
    for (let i = 1; i <= count; i++) {
      const demoInfo = {
        name: `${answers.prefix} ${i}`,
        category: answers.category,
        folderName: null,
        includeJS: true,
        openInEditor: false
      };
      
      await this.createDemo(demoInfo);
    }
    
    console.log(chalk.green(`\n✅ 批量生成完成！共生成 ${count} 个案例`));
  }

  async updateDemoJS(name, folderName, category) {
    const demoJSPath = path.join(__dirname, '..', 'src', 'scripts', 'demo.js');
    
    if (!fs.existsSync(demoJSPath)) {
      console.warn(chalk.yellow('⚠️  demo.js 文件不存在，跳过更新'));
      return;
    }

    try {
      let content = fs.readFileSync(demoJSPath, 'utf8');
      
      // 找到数组结束的位置
      const arrayEndIndex = content.lastIndexOf(']');
      if (arrayEndIndex === -1) {
        console.warn(chalk.yellow('⚠️  无法找到demo.js中的数组结束位置，跳过更新'));
        return;
      }

      // 生成新的案例数据
      const newDemo = `  {
    id: generateId,
    name: "${name}",
    category: Categories.${this.getCategoryConstant(category)},
    preview: "images/previews/${folderName}.webp",
    path: "./demos/${folderName}/index.html",
  },
`;

      // 在数组结束前插入新案例
      const beforeArrayEnd = content.substring(0, arrayEndIndex);
      const afterArrayEnd = content.substring(arrayEndIndex);
      
      const updatedContent = beforeArrayEnd + newDemo + afterArrayEnd;
      
      // 写回文件
      fs.writeFileSync(demoJSPath, updatedContent);
      
    } catch (error) {
      console.warn(chalk.yellow(`⚠️  更新demo.js失败: ${error.message}`));
    }
  }

  getCategoryConstant(category) {
    const categoryMap = {
      'buttons': 'Button',
      'animations': 'Animation',
      'loadings': 'Loading',
      'navigations': 'Navigation',
      'cards': 'Card',
      'forms': 'Form',
      'layouts': 'Layout',
      'icons': 'Icon',
      'transitions': 'Transition'
    };
    return categoryMap[category] || 'Animation';
  }

}

// 命令行接口
if (require.main === module) {
  const generator = new DemoGenerator();
  
  const args = process.argv.slice(2);
  
  if (args.includes('--batch')) {
    generator.generateBatch().catch(console.error);
  } else {
    generator.generate().catch(console.error);
  }
}

module.exports = DemoGenerator;
